﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using System.Data;
using CSP.LoggingEngine;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using Microsoft.SharePoint.Publishing;
using Microsoft.Security.Application;



namespace CSP.WebParts.UserControls
{
    public class CSPKeyAttraction
    {
        public string Title { get; set; }
        public string Address { get; set; }
        public string Location { get; set; }
    }

    /// <summary>
    /// Gets the list of the Key Attractions
    /// </summary>  
    public class CSPKeyAttractionsWUC : CSPBaseWUC
    {
        #region Properties
        public string DataSource { get; set; }
        public string IconsLibraryUrl { get; set; }
        public string ListSite { get; set; }
        public string ListName { get; set; }
        #endregion

        #region Members
        public List<CSPKeyAttraction> KeyAttractions;
        protected Repeater rptKeyAttractions;
        DataTable dt;
        string category,newCategory;
        int pos;
        protected string _lastCategory = string.Empty;
        #endregion


        #region Methods
        /// <summary>
        /// Fired on page load
        /// </summary>  
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            try
            {
                if (!Page.IsPostBack)
                {
                    this.LoadData();
                }
            }          
            catch (CSP.Core.CSPException cspex)
            {
                throw cspex;
            }
            catch (Exception ex)
            {
                this.LogMessage(this.LoadResource(WebPartConstants.CSPKeyAttractionsLoadErrorMessage), this.GetType().Name, ex);
                throw ex;
            }

        }

        /// <summary>
        /// Gets the list of the key attractions. they are stored in a sharepoint list
        /// </summary>  
        private void LoadData()
        {
            string datasource = "<items>";
            try
            {

                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(SPContext.Current.Site.Url))
                    {
                        SPWeb web = site.AllWebs[this.ListSite];
                        SPList list = web.Lists[this.ListName];
                        SPQuery spq = new SPQuery();
                        spq.Query = "<OrderBy><FieldRef Name=\"_Category\" /></OrderBy>";

                        foreach (SPListItem li in list.GetItems(spq))
                        {
                            datasource += "<item>";
                            datasource += string.Format("<title>{0}</title>", li.Title.ToString());
                            datasource += string.Format("<category>{0}</category>", li["Category"].ToString());
                            datasource += string.Format("<location>{0}</location>", li["Location"].ToString());
                            datasource += string.Format("<icon>{0}</icon>", li["Icon"].ToString());
                            datasource += "</item>";
                        }
                        datasource += "</items>";

                        this.rptKeyAttractions.DataSource = datasource;
                        this.rptKeyAttractions.DataBind(); 
                    }
                });
            }
            catch (CSP.Core.CSPException cspex)
            {
                throw cspex;
            }
            catch (Exception ex)
            {
                this.LogMessage(this.LoadResource(WebPartConstants.CSPGenericErrorMessage), this.GetType().Name, ex);
                throw ex;
            }
        }


        /// <summary>
        /// Fired on page create child controls
        /// </summary>  
        protected override void CreateChildControls()
        {

            base.CreateChildControls();
            try
            {
                this.rptKeyAttractions.ItemDataBound +=new RepeaterItemEventHandler(rptKeyAttractions_ItemDataBound);
            }          
            catch (CSP.Core.CSPException cspex)
            {
                throw cspex;
            }
            catch (Exception ex)
            {
                this.LogMessage(this.LoadResource(WebPartConstants.CSPKeyAttractionsCreateChildControlsErrorMessage), this.GetType().Name, ex);
                throw ex;
            }
        }

        /// <summary>
        /// Fired on repeater item data bound
        /// </summary>  
        private void rptKeyAttractions_ItemDataBound(Object Sender, RepeaterItemEventArgs e)
        {
            try
            {
                System.Xml.XmlDocument xdoc = new System.Xml.XmlDocument();
                xdoc.LoadXml(this.rptKeyAttractions.DataSource.ToString());
                System.Data.DataSet ds = new System.Data.DataSet();
                ds.ReadXml(new System.Xml.XmlNodeReader(xdoc));
                //rptKeyAttractions.DataSource = ds;
                //if (ds.Tables.Count == 1)
                //    rptKeyAttractions.DataBind();


                if (ds.Tables.Count > 0)
                {
                    dt = ds.Tables[0]; // ((DataSet)(this.rptKeyAttractions.DataSource)).Tables[0];
                    if (e.Item.ItemIndex > -1 && e.Item.ItemIndex < ds.Tables[0].Rows.Count)
                    {
                        try
                        {
                            string title = AntiXss.HtmlEncode(dt.Rows[e.Item.ItemIndex]["Title"].ToString());
                            newCategory = dt.Rows[e.Item.ItemIndex]["Category"].ToString();
                            string location = AntiXss.HtmlEncode(dt.Rows[e.Item.ItemIndex]["Location"].ToString());
                            string icon = dt.Rows[e.Item.ItemIndex]["Icon"].ToString();

                            if (newCategory != _lastCategory)
                            {
                                ((Label)(e.Item.FindControl("rptCategory"))).Text = newCategory;
                                (e.Item.FindControl("rptCategorySpan")).Visible = true;
                            }
                            ((Label)(e.Item.FindControl("rptTitle"))).Text = "<a href=\"javascript:FindAttraction('" + title + "','" + location + "','" + IconsLibraryUrl + "/" + icon + ".gif')\">" + title + "</a>";
                            _lastCategory = newCategory;
                        }
                        catch { }
                    }
                }
            }           
            catch (CSP.Core.CSPException cspex)
            {
                throw cspex;
            }
            catch (Exception ex)
            {
                this.LogMessage(this.LoadResource(WebPartConstants.CSPKeyAttractionsItemDataBoundErrorMessage), this.GetType().Name, ex);
                throw ex;
            }

        }
        #endregion




    }
}
